
#import "TSO_Setup.h"
#import "TSO_Setup_TableViewCell.h"
#import "DBHelper.h"

@implementation TSO_Setup

@synthesize delegate;
@synthesize delegate_UIPopoverController;

#pragma mark -
#pragma mark  物件初始化

-(id)initWithallcountry:(NSMutableArray *)allcountrys {
	self= [super init];
	if (self) {
		allcountry=allcountrys;
	}
	return self;	 	
}

#pragma mark -
#pragma mark  啓動畫面開始程式
- (void)loadView {
	
	
	UIView *mainview;
	mainview=[[UIView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
	self.view=mainview;
    [mainview release];
    
	self.view.backgroundColor=[UIColor lightTextColor];	
	
	UINavigationBar *nav;
	nav = [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 48.0f)];	
	
	UIBarButtonItem *barButton ;
	barButton = [[UIBarButtonItem alloc] initWithTitle:  NSLocalizedString(@"Done",@"Done")  style:UIBarButtonItemStylePlain target:self action:@selector(slideOut)];
	UINavigationItem *item;
	item = [[UINavigationItem alloc] initWithTitle:  @"程式交易最佳化參數設定" ];
	[item setRightBarButtonItem: barButton];
	[nav pushNavigationItem:item animated:NO];	
	[item release];
	
	myTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 48.0f,320.f, 412.0f)  style:UITableViewStyleGrouped];
	//myTable.frame=CGRectMake(0.0f, 48.0f, 320.0f, 200.0f);
	myTable.dataSource = self;	//連結資料 UITableViewDataSource
	myTable.delegate=self; //連結動作 UITableViewDelegate	
	 [self.view addSubview:myTable];
    [mainview addSubview:nav ];	
	[nav release];
    
	//選項
	SearchCondition = [[NSArray arrayWithObjects:@"是否進行最佳化參數",@"最佳化時間週期",@"最佳化起始日期",@"最佳化模型",@"單一模型選項",@"停損出場率(%)",@"買賣手續費率(%)",@"多空或雙向策略",@"進出場時間選擇",@"進出場價格選擇",@"進出場數量選擇", @"是否寫入TXT檔",@"是否顯示參數",@"資料庫重置 清除最佳化資料",@"建立最佳化名單",@"輸出最佳化資料",@"建立維護資料名單", nil] retain];	
    
	//設定選擇扭==交易策略
	//最佳化模型
	tradesystemaray=[[NSMutableArray alloc]init];
	[tradesystemaray addObject:@"MESA"];
	[tradesystemaray addObject:@"LF"];
	
	//策略內部
	tradeIndex=[[NSMutableArray alloc]init];
	[tradeIndex addObject:@"1"];
	[tradeIndex addObject:@"2"];
	[tradeIndex addObject:@"3"];	
	
	//停損出場率(%)
	stopratearay=[[NSMutableArray alloc]init];
	
	[stopratearay addObject:@"0.01"];
	[stopratearay addObject:@"0.05"];
	[stopratearay addObject:@"0.1"];	
	[stopratearay addObject:@"0.15"];	
	[stopratearay addObject:@"0.2"];	
	//買賣手續費率(%)
	costfeeratearay=[[NSMutableArray alloc]init];
	[costfeeratearay addObject:@"0.001"];
	[costfeeratearay addObject:@"0.00125"];	
	[costfeeratearay addObject:@"0.0015"];		
	[costfeeratearay addObject:@"0.00175"];	
	[costfeeratearay addObject:@"0.002"];			
	//買賣或是兩者都有的交易
	buysellboth=[ [NSMutableArray  alloc] init];
	[buysellboth addObject:@"僅作多"];
	[buysellboth addObject:@"僅作空"];
	[buysellboth addObject:@"多空雙向"];	
	
	
	enterTime=[[NSMutableArray alloc] init];
	[enterTime addObject:@"當日"];
	[enterTime addObject:@"後一日"];
	[enterTime addObject:@"後二日"];	
	 enterprice=[[NSMutableArray alloc] init];
	[enterprice addObject:@"開盤價"];
 	[enterprice addObject:@"收盤價"];
	[enterprice addObject:@"最高價"];
 	[enterprice addObject:@"最低價"];	
	
	enternumber=[[NSMutableArray alloc] init];
	[enternumber addObject:@"單位:1"];
	[enternumber addObject:@"金額:5萬"];
	[enternumber addObject:@"金額:1百萬"];
	
	//取出設定檔資料
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	 		
	
	pick=[[UIPickerView alloc ]initWithFrame:CGRectMake(0.0f, 246.0f, 320.0f, 216.0f)];
	pick.delegate=self;
	pick.showsSelectionIndicator=YES;
	[pick reloadAllComponents];
	
	//最佳化模型	
 
		//NSLog(@"qqqqqqno");
		[pick selectRow:[tradesystemaray indexOfObject:(NSString *) [prefs objectForKey:@"OptimizeTradeSystem"] ] inComponent:0 animated:YES];	
	 
	//策略內部	
	 
		//NSLog(@"qqqqqqno");
		[pick selectRow:[tradeIndex indexOfObject:(NSString *) [prefs objectForKey:@"tradeindex"] ] inComponent:0 animated:YES];	
 
	
	//停損出場率(%)	
	 
		[pick selectRow:[stopratearay indexOfObject:(NSString *) [prefs objectForKey:@"Optimizestopratearay"] ] inComponent:0 animated:YES];	
	 
	//買賣手續費率(%)
  		[pick selectRow:[costfeeratearay indexOfObject:(NSString *) [prefs objectForKey:@"Optimizescostfeeratearay"] ] inComponent:0 animated:YES];	
	 	
	
	//買賣或是兩者都有的交易	
	 
		[pick selectRow:[buysellboth indexOfObject:(NSString *) [prefs objectForKey:@"buysellboth"] ] inComponent:0 animated:YES];	
	 
	
	//進出場時間選擇	
	 
		[pick selectRow:[enterTime indexOfObject:(NSString *) [prefs objectForKey:@"enterTime"] ] inComponent:0 animated:YES];	
	 	
	//進出場價格選擇	
	 
	 
		[pick selectRow:[enterprice indexOfObject:(NSString *) [prefs objectForKey:@"enterprice"] ] inComponent:0 animated:YES];	
	 		
	
	//進出場數量選擇	
	 
	 
		[pick selectRow:[enternumber indexOfObject:(NSString *) [prefs objectForKey:@"enternumber "] ] inComponent:0 animated:YES];	
	 		
	
	
	
	pick.hidden=YES;
	[self.view addSubview:pick];
	
	//設定日期選擇扭
	
	datepick=[[UIDatePicker alloc] initWithFrame:CGRectMake(0.0f, 246.0f, 320.0f, 216.0f)];
	datepick.datePickerMode=UIDatePickerModeDate;
	[datepick addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
	
	if ([prefs objectForKey:@"startOptimizeDate"]==nil) {
	    //設定全部時間
		NSTimeInterval secondsAgo = -timeIntervalForNumberOfWeeks(520); //預設10年期資料開始
		NSDate *aStartDate = [NSDate dateWithTimeIntervalSinceNow:secondsAgo]; 		
		
		NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
		[prefs setObject:aStartDate forKey:@"startOptimizeDate"];
		[prefs synchronize];			
		
	}
	 
    datepick.date=[prefs objectForKey:@"startOptimizeDate"] ;	
	[self.view addSubview:datepick];
	
	datepick.hidden=YES;
	
	
}



#pragma mark -
#pragma mark  滑出
-(void)slideOut{
		
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        [delegate_UIPopoverController dismissPopoverAnimated:YES]; 
    }    
	else{
       [self.delegate TSO_SetupDidFinish:self];    
    }
    
    
    
}


#pragma mark -
#pragma mark  表格事件

//區塊數量
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 1;
}
//區塊與列數量
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
	switch (section) {
		case 0:
			return [SearchCondition count];
			break;
		 		 
	} 
	return 2;
}
//表格內容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	static NSString *CellIdentifier = @"TableCellAddStockWatchList";
    
    TSO_Setup_TableViewCell *cell ;
	
	 
	cell = [[[TSO_Setup_TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
   
	
	switch (indexPath.section) {
		case 0:{
			cell.textLabel.text = [SearchCondition objectAtIndex:indexPath.row];
		   	
			
			if ([cell.textLabel.text isEqualToString:@"是否進行最佳化參數"]) {
				//是否開啓最佳化 @"Search By Name" tag=100 
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
				UISwitch *onoff;
				onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
				onoff.tag=100; //isActiveOptimize
				[onoff addTarget: self action: @selector(switchChange:) forControlEvents: UIControlEventValueChanged];
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				[prefs  boolForKey:@"isActiveOptimize" ];
				
				onoff.on=(BOOL)[prefs  boolForKey:@"isActiveOptimize" ];
				
				[self.view addSubview: onoff];
				cell.accessoryView=onoff;
				[onoff release];				
				
			}
		 		
			if ([cell.textLabel.text isEqualToString:@"是否寫入TXT檔"]) {
				//是否開啓最佳化 @"Search By Name" tag=100 
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
				UISwitch *onoff;
				onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
				onoff.tag=300; //isActiveOptimize
				[onoff addTarget: self action: @selector(switchChange:) forControlEvents: UIControlEventValueChanged];
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				[prefs  boolForKey:@"isWriteToTXT" ];
				
				onoff.on=(BOOL)[prefs  boolForKey:@"isWriteToTXT" ];
				
				[self.view addSubview: onoff];
				cell.accessoryView=onoff;
				[onoff release];				
				
			}	
			if ([cell.textLabel.text isEqualToString:@"是否顯示參數"]) {
				//是否開啓最佳化 @"Search By Name" tag=100 
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
				UISwitch *onoff;
				onoff = [[UISwitch alloc] initWithFrame: CGRectZero];
				onoff.tag=400; //isActiveOptimize
				[onoff addTarget: self action: @selector(switchChange:) forControlEvents: UIControlEventValueChanged];
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				[prefs  boolForKey:@"isShowPara" ];
				
				onoff.on=(BOOL)[prefs  boolForKey:@"isShowPara" ];
				
				[self.view addSubview: onoff];
				cell.accessoryView=onoff;
				[onoff release];				
				
			}						
			
			
			
			
			if ([cell.textLabel.text isEqualToString:@"最佳化時間週期"]) {
				//讓表格的列不會被使用者點選時出現藍色的狀態
				cell.selectionStyle=UITableViewCellSelectionStyleNone;
				
				
				NSArray *aaa=[NSArray arrayWithObjects:@"日",@"週",@"月",nil];
				UISegmentedControl *seg;
				seg=[[UISegmentedControl alloc] initWithItems:aaa];
				seg.frame=CGRectMake(0.0,0.0, 95.0, 30.0);
				[seg addTarget: self action: @selector(segChange:) forControlEvents: UIControlEventValueChanged];
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				seg.selectedSegmentIndex= [prefs integerForKey:@"isActiveOptimize_dwm" ];				
			    cell.accessoryView=seg;								
				
			}
			if ([cell.textLabel.text isEqualToString:@"最佳化起始日期"]) {
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];				
				
				NSDateFormatter* df = [[NSDateFormatter alloc]init];
				[df setDateFormat:@"yyyy/MM/dd"];
				NSString *result = [df stringFromDate:[prefs objectForKey:@"startOptimizeDate"]];	
				cell.name.text=result;		
				[df release];
				 
				
				
			}
			if ([cell.textLabel.text isEqualToString:@"最佳化模型"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"OptimizeTradeSystem"];				
			 	
				
			}		
			if ([cell.textLabel.text isEqualToString:@"單一模型選項"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"tradeindex"];				
			 	
				
			}		
			
			if ([cell.textLabel.text isEqualToString:@"多空或雙向策略"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"buysellboth"];				
			 	
				
			}					
			if ([cell.textLabel.text isEqualToString:@"進出場時間選擇"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"enterTime"];				
			 	
				
			}	
			if ([cell.textLabel.text isEqualToString:@"進出場價格選擇"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"enterprice"];				
			 	
				
			}				
			if ([cell.textLabel.text isEqualToString:@"進出場數量選擇"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"enternumber"];				
			 	
				
			}				
			
			if ([cell.textLabel.text isEqualToString:@"停損出場率(%)"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"Optimizestopratearay"];				
				//[pick selectRow:[stopratearay indexOfObject:cell.name.text ] inComponent:0 animated:YES];	
				
				
			}				
			if ([cell.textLabel.text isEqualToString:@"買賣手續費率(%)"]) {
				
				//取出設定檔資料
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				cell.name.text=(NSString *) [prefs objectForKey:@"Optimizescostfeeratearay"];				
				//[pick selectRow:[costfeeratearay indexOfObject:cell.name.text ] inComponent:0 animated:YES];	
				
				
			}				
			
			
			
			break;
		}
		  
			
			
			
	}
	
	if ([cell.textLabel.text isEqualToString:@"最佳化起始日期"] 
		|| [cell.textLabel.text isEqualToString:@"最佳化模型"] 
		|| [cell.textLabel.text isEqualToString:@"多空或雙向策略"] 
		|| [cell.textLabel.text isEqualToString:@"停損出場率(%)"] 
		|| [cell.textLabel.text isEqualToString:@"買賣手續費率(%)"] 
		|| [cell.textLabel.text isEqualToString:@"進出場時間選擇"] 
		|| [cell.textLabel.text isEqualToString:@"單一模型選項"] 
		|| [cell.textLabel.text isEqualToString:@"進出場價格選擇"] 		
		|| [cell.textLabel.text isEqualToString:@"進出場數量選擇"]){
		
		cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
	}	
	else {
		cell.accessoryType=UITableViewCellAccessoryNone;		
	}	
	return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
	TableSelectRow=indexPath.row;	
	if (indexPath.row==2) {
		datepick.hidden=NO;
		pick.hidden=YES;
		 myTable.frame=CGRectMake(0.0f, 48.0f, 320.0f, 200.0f);		
	}
	else if(indexPath.row==3 || indexPath.row==4 || indexPath.row==5 || indexPath.row==6 || indexPath.row==7 || indexPath.row==8  || indexPath.row==9 || indexPath.row==10){
		
		//捲軸調整
		switch (indexPath.row) {
			case 3:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				 					
				[pick selectRow:[tradesystemaray indexOfObject:[prefs objectForKey:@"OptimizeTradeSystem"]] inComponent:0 animated:YES];				
				
				break;
			}
			case 4:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				
				[pick selectRow:[tradeIndex indexOfObject:[prefs objectForKey:@"tradeindex"]] inComponent:0 animated:YES];				
				
				break;
			}				
				
			case 5:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				
				[pick selectRow:[stopratearay indexOfObject:[prefs objectForKey:@"Optimizestopratearay"]] inComponent:0 animated:YES];				
				
				break;
			}
			case 6:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				
				[pick selectRow:[costfeeratearay indexOfObject:[prefs objectForKey:@"Optimizescostfeeratearay"]] inComponent:0 animated:YES];				
				
				break;
			}				
			case 7:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				
				[pick selectRow:[buysellboth indexOfObject:[prefs objectForKey:@"buysellboth"]] inComponent:0 animated:YES];				
				
				break;
			}		
			case 8:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				
				[pick selectRow:[enterTime indexOfObject:[prefs objectForKey:@"enterTime"]] inComponent:0 animated:YES];				
				
				break;
			}	
			case 9:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				
				[pick selectRow:[enterprice indexOfObject:[prefs objectForKey:@"enterprice"]] inComponent:0 animated:YES];				
				
				break;
			}	
			case 10:{
				NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
				
				[pick selectRow:[enternumber indexOfObject:[prefs objectForKey:@"enternumber"]] inComponent:0 animated:YES];				
				
				break;
			}	
				
			default:
				break;
		}
		
		
		
		
		datepick.hidden=YES;
		pick.hidden=NO;		
		[pick reloadAllComponents];
		 myTable.frame=CGRectMake(0.0f, 48.0f, 320.0f, 200.0f);
	}
	else if(indexPath.row==13){
		 
		// 最佳化參數歸零
		[self resetOptimizePara];	
		
		UIAlertView *ia;
		ia=[[UIAlertView alloc] initWithTitle:@"資料庫處理" message:@"資料庫清除與增加完成" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
		[ia show];				
		
	}
	else if(indexPath.row==14){
		//標記:Add Target need Program        
        //建立最佳化名冊
        [self opt_datasql_code_name:@"SP500" titels:@"最佳化群組_" ]; 
        [self opt_datasql_code_name:@"DOW30" titels:@"最佳化群組_" ];        
		[self opt_datasql_code_name:@"HK" titels:@"最佳化群組_" ];
		[self opt_datasql_code_name:@"US" titels:@"最佳化群組_"];
		[self opt_datasql_code_name:@"FU" titels:@"最佳化群組_" ];
		[self opt_datasql_code_name:@"CH" titels:@"最佳化群組_"];
		[self opt_datasql_code_name:@"TW" titels:@"最佳化群組_"];
		[self opt_datasql_code_name:@"IND" titels:@"最佳化群組_" ];	
		[self opt_datasql_code_name:@"KS" titels:@"最佳化群組_" ];			
		[self opt_datasql_code_name:@"ETF" titels:@"最佳化群組_" ];	
		[self opt_datasql_code_name:@"UK" titels:@"最佳化群組_" ];
		[self opt_datasql_code_name:@"CN" titels:@"最佳化群組_" ];   
        [self opt_datasql_code_name:@"KS" titels:@"最佳化群組_" ];        
        [self opt_datasql_code_name:@"SI" titels:@"最佳化群組_" ];          
        [self opt_datasql_code_name:@"AX" titels:@"最佳化群組_" ]; 
        [self opt_datasql_code_name:@"PA" titels:@"最佳化群組_" ];          
        [self opt_datasql_code_name:@"GR" titels:@"最佳化群組_" ];         
        [self opt_datasql_code_name:@"INDIA" titels:@"最佳化群組_" ];        
        [self opt_datasql_code_name:@"NZ" titels:@"最佳化群組_" ];         
        [self opt_datasql_code_name:@"MI" titels:@"最佳化群組_" ];          
        [self opt_datasql_code_name:@"SA" titels:@"最佳化群組_" ];  
        [self opt_datasql_code_name:@"MX" titels:@"最佳化群組_" ];         
        
		UIAlertView *ia;
		ia=[[UIAlertView alloc] initWithTitle:@"資料庫處理" message:@"建立最佳化名冊 完成" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
		[ia show];			
		
		
	}	
	
    else if(indexPath.row==15){
		// 輸出最佳化資料		
		 		
		[self opt_data_output:@"LF" dwm:@"d"];				
		[self opt_data_output:@"MESA" dwm:@"d"];
        		
		
		UIAlertView *ia;
		ia=[[UIAlertView alloc] initWithTitle:@"資料庫處理" message:@"輸出最佳化資料完成" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
		[ia show];			
		
	}
	
	else if(indexPath.row==16){
		
        //標記:增加一個市場，可以盤後回補當日資料 4 維護資料        
        //標記:Add Target need Program        
       
        //維護資料
		 
		[self opt_datasql_code_name:@"TW" titels:@"維護資料_"];
		[self opt_datasql_code_name:@"HK" titels:@"維護資料_"];	
        [self opt_datasql_code_name:@"US" titels:@"維護資料_"];
		[self opt_datasql_code_name:@"CH" titels:@"維護資料_"];
		[self opt_datasql_code_name:@"KS" titels:@"維護資料_"];		
	    [self opt_datasql_code_name:@"ETF" titels:@"維護資料_"];		
        [self opt_datasql_code_name:@"UK" titels:@"維護資料_"];	
        [self opt_datasql_code_name:@"CN" titels:@"維護資料_"];	        
        [self opt_datasql_code_name:@"KS" titels:@"維護資料_"];	
        [self opt_datasql_code_name:@"SI" titels:@"維護資料_"];	        
        [self opt_datasql_code_name:@"AX" titels:@"維護資料_"];
        [self opt_datasql_code_name:@"PA" titels:@"維護資料_"];	        
        [self opt_datasql_code_name:@"GR" titels:@"維護資料_"];	        
        
        
		UIAlertView *ia;
		ia=[[UIAlertView alloc] initWithTitle:@"資料庫處理" message:@"建立維護資料名單 完成" delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil];
		[ia show];			
		
		
	}	
}

#pragma mark -
#pragma mark  輸出最佳化資料
-(void)opt_data_output:(NSString *)tradesystem dwm:(NSString *)adwm {
	NSAutoreleasePool *pool=[[NSAutoreleasePool alloc] init];
	
	for (int i=0; i<3; i++) {
		 
	    NSString *aindex;
		aindex=[NSString stringWithFormat:@"%i",i];
		
		//建立目錄
		NSString *path;
		path=[NSString stringWithFormat:@"Documents/%@_%@_%@",tradesystem,aindex,adwm];
		//所有表格
		NSString *path_all;
		path_all=[NSString stringWithFormat:@"Documents/%@_%@_%@/all",tradesystem,aindex,adwm];
		//單一參數檔案
		NSString *path_single;
		path_single=[NSString stringWithFormat:@"Documents/%@_%@_%@/single",tradesystem,aindex,adwm];	
		//分類檔案
		//NSString *path_class;
		//path_class=[NSString stringWithFormat:@"Documents/%@_%@_%@/class",tradesystem,aindex,adwm];	
		
		NSFileManager *filemanager=[NSFileManager defaultManager];
		
		NSString *newdirpath=[NSHomeDirectory() stringByAppendingPathComponent:path];
		NSString *newdirpath_all=[NSHomeDirectory() stringByAppendingPathComponent:path_all];
		NSString *newdirpath_single=[NSHomeDirectory() stringByAppendingPathComponent:path_single];	
		//NSString *newdirpath_class=[NSHomeDirectory() stringByAppendingPathComponent:path_class];		
		
		[filemanager createDirectoryAtPath:newdirpath withIntermediateDirectories:YES attributes:nil error:nil];
		[filemanager createDirectoryAtPath:newdirpath_all withIntermediateDirectories:YES attributes:nil error:nil];
		[filemanager createDirectoryAtPath:newdirpath_single withIntermediateDirectories:YES attributes:nil error:nil];
		//[filemanager createDirectoryAtPath:newdirpath_class withIntermediateDirectories:YES attributes:nil error:nil];
		
		
		//從資料庫中 取出資料
		
		const char *sql = NULL;	
		NSString *tsql=@"";
		
		
		if ([tradesystem isEqualToString:@"MESA"]){
			tsql=@"SELECT id,code,FastLim,SlowLim,winpercentage,yearreturn,count,startdate,enddate,id_class FROM ";
			
		}
		else if([tradesystem isEqualToString:@"LF"]){
			tsql=@"SELECT id,code,BRangeDay,SRangeDay,Bratio,Sratio,winpercentage,yearreturn,count,startdate,enddate,id_class FROM ";
		}		
		tsql=[tsql stringByAppendingString:tradesystem];
		tsql=[tsql stringByAppendingString:@"_"];
		tsql=[tsql stringByAppendingString:aindex];
		tsql=[tsql stringByAppendingString:@"_"];
		tsql=[tsql stringByAppendingString:adwm];
		
		
		
		sql=[tsql UTF8String];	
		
		//啓動資料庫檔案 輸入檔名與副執行檔名稱與全名
		
		NSString *ver;
		ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
		ver=[ver stringByReplacingOccurrencesOfString:@"." withString:@"_"];
		NSString *filename;
		filename=@"data_";
		filename=[filename stringByAppendingString:ver];
		NSString *filenamexx;
		filenamexx=@"sqlite3";
		NSString *fullfilename;
		fullfilename=[filename stringByAppendingString:@"."];
		fullfilename=[fullfilename stringByAppendingString:filenamexx];
		DBHelper *helper =[DBHelper newInstance:filename andEXT:filenamexx andfullname:fullfilename];		
		sqlite3 *database = [helper openDatabase]; 
		//[helper release];
        sqlite3_stmt *stm;
		//NSLog(@"nnn=%@",tradesystem);		
		NSString *write_all;
		
		write_all=[NSString stringWithFormat:@"%@_%@_%@\n",tradesystem,aindex,adwm];		
		if ([tradesystem isEqualToString:@"MESA"]){
			
			write_all=[write_all stringByAppendingString: @"code\tFastLim\tSlowLim\twinpercentage\tyearreturn\tcount\tstartdate\tenddate\tid_class\tcountry\n"] ;
	
		}
		else if([tradesystem isEqualToString:@"LF"]){
			write_all=[write_all stringByAppendingString: @"code\tBRangeDay\tSRangeDay\tBratio\tSratio\twinpercentage\tyearreturn\tcount\tstartdate\tenddate\tid_class\tcountry\n"];
		}

		NSString *code;
		
		NSString *FastLim=@"";
		NSString *SlowLim=@"";
		
		NSString *BRangeDay=@"";
		NSString *SRangeDay=@"";
		NSString *Bratio=@"";
		NSString *Sratio=@"";
		
		NSString *winpercentage=@"";
		NSString *yearreturn=@"";
		NSString *count=@"";
		NSString *startdate=@"";
		NSString *enddate=@"";
		NSString *id_class=@"";
		NSString *id_country=@"";
		
		if(sqlite3_prepare_v2(database, sql, strlen(sql), &stm, NULL)== SQLITE_OK) {	
			//NSLog(@"have data");
			while(sqlite3_step(stm) ==SQLITE_ROW)
			{		
				//取出參數				
				char *field1=(char *)sqlite3_column_text(stm, 1);
				NSString *ss1=[[[NSString alloc]initWithUTF8String:field1] autorelease];
				NSArray *name=[ss1 componentsSeparatedByString:@"."];
				code=ss1;
			    if ([tradesystem isEqualToString:@"MESA"]){
					
					//讀取參數
					char *field2=(char *)sqlite3_column_text(stm,2);
					FastLim=[[[NSString alloc]initWithUTF8String:field2] autorelease];
					char *field3=(char *)sqlite3_column_text(stm, 3);
					SlowLim=[[[NSString alloc]initWithUTF8String:field3] autorelease];
					
					char *field4=(char *)sqlite3_column_text(stm,4);
					winpercentage=[[[NSString alloc]initWithUTF8String:field4] autorelease];
					char *field5=(char *)sqlite3_column_text(stm, 5);
					yearreturn=[[[NSString alloc]initWithUTF8String:field5] autorelease];
					char *field6=(char *)sqlite3_column_text(stm,6);
					count=[[[NSString alloc]initWithUTF8String:field6] autorelease];
					char *field7=(char *)sqlite3_column_text(stm, 7);
					startdate=[[[NSString alloc]initWithUTF8String:field7] autorelease];
					char *field8=(char *)sqlite3_column_text(stm,8);
					enddate=[[[NSString alloc]initWithUTF8String:field8] autorelease];
					char *field9=(char *)sqlite3_column_text(stm, 9);
					id_class=[[[NSString alloc]initWithUTF8String:field9] autorelease];
					
					
				}				
				else if([tradesystem isEqualToString:@"LF"]){				
					//讀取參數 BRangeDay,SRangeDay,Bratio,Sratio
					char *field2=(char *)sqlite3_column_text(stm,2);
					 BRangeDay=[[[NSString alloc]initWithUTF8String:field2] autorelease];
					char *field3=(char *)sqlite3_column_text(stm, 3);
					 SRangeDay=[[[NSString alloc]initWithUTF8String:field3] autorelease];
					char *field4=(char *)sqlite3_column_text(stm,4);
					 Bratio=[[[NSString alloc]initWithUTF8String:field4] autorelease];
					char *field5=(char *)sqlite3_column_text(stm, 5);
					 Sratio=[[[NSString alloc]initWithUTF8String:field5] autorelease];
					
					
					char *field6=(char *)sqlite3_column_text(stm,6);
					winpercentage=[[[NSString alloc]initWithUTF8String:field6] autorelease];
					char *field7=(char *)sqlite3_column_text(stm, 7);
					yearreturn=[[[NSString alloc]initWithUTF8String:field7] autorelease];
					char *field8=(char *)sqlite3_column_text(stm,8);
					count=[[[NSString alloc]initWithUTF8String:field8] autorelease];
					char *field9=(char *)sqlite3_column_text(stm, 9);
					startdate=[[[NSString alloc]initWithUTF8String:field9] autorelease];
					char *field10=(char *)sqlite3_column_text(stm,10);
					enddate=[[[NSString alloc]initWithUTF8String:field10] autorelease];
					char *field11=(char *)sqlite3_column_text(stm, 11);
					id_class=[[[NSString alloc]initWithUTF8String:field11] autorelease];
					
				}
				
				
				//製作參數用於奇狐
				if ([name count]==1) {
					id_country=@"US";
					
					//美國
					//製作主目錄
					NSString *path_single_tradesystem;
					path_single_tradesystem=[NSString stringWithFormat:@"Documents/%@_%@_%@/single/%@",tradesystem,aindex,adwm,@"US"];				
					NSString *newdirpath_single_tradesystem=[NSHomeDirectory() stringByAppendingPathComponent:path_single_tradesystem];					
					[filemanager createDirectoryAtPath:newdirpath_single_tradesystem withIntermediateDirectories:YES attributes:nil error:nil];
					//NSLog(@"美國=%@",ss1);
					
					//輸出檔案
					//製作single
					if ([tradesystem isEqualToString:@"MESA"]){
						
						
						
						//寫入檔名
						NSString *newdirpath_single_tradesystem_ParaFile=[newdirpath_single_tradesystem stringByAppendingFormat:@"/%@.txt",[name objectAtIndex:0]];
						//
						NSString *para=[NSString stringWithFormat:@"%@\r\n\%@",FastLim,SlowLim];
						[para writeToFile:newdirpath_single_tradesystem_ParaFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
						
						
					}				
					else if([tradesystem isEqualToString:@"LF"]){
							
						
						
						//寫入檔名
						NSString *newdirpath_single_tradesystem_ParaFile=[newdirpath_single_tradesystem stringByAppendingFormat:@"/%@.txt",[name objectAtIndex:0]];
						//
						NSString *para=[NSString stringWithFormat:@"%@\r\n\%@\r\n%@\r\n%@\n",BRangeDay,SRangeDay,Bratio,Sratio];
						[para writeToFile:newdirpath_single_tradesystem_ParaFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
						
						
						
						
						
						
						
						
						
					}						
					
				}
				else if([name count]==2){
					//非美國
					//製作主目錄
					// NSLog(@"非美國=%@",ss1);					
					id_country=[name objectAtIndex:1];					
					NSString *path_single_tradesystem;
					path_single_tradesystem=[NSString stringWithFormat:@"Documents/%@_%@_%@/single/%@",tradesystem,aindex,adwm,[name objectAtIndex:1]];				
					NSString *newdirpath_single_tradesystem=[NSHomeDirectory() stringByAppendingPathComponent:path_single_tradesystem];					
					[filemanager createDirectoryAtPath:newdirpath_single_tradesystem withIntermediateDirectories:YES attributes:nil error:nil];
					
					 
					//製作single
					//NSLog(@"bbbb=%@",tradesystem);
					if ([tradesystem isEqualToString:@"MESA"]){
						//寫入檔名
						NSString *newdirpath_single_tradesystem_ParaFile=[newdirpath_single_tradesystem stringByAppendingFormat:@"/%@.txt",[name objectAtIndex:0]];
						//\r\n 主要是用來windows換行可以顯示
						NSString *para=[NSString stringWithFormat:@"%@\r\n\%@",FastLim,SlowLim];
						[para writeToFile:newdirpath_single_tradesystem_ParaFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
					}				
					else if([tradesystem isEqualToString:@"LF"]){
						//寫入檔名
						//NSLog(@"aaaaa");
						NSString *newdirpath_single_tradesystem_ParaFile=[newdirpath_single_tradesystem stringByAppendingFormat:@"/%@.txt",[name objectAtIndex:0]];
						//
						NSString *para=[NSString stringWithFormat:@"%@\r\n\%@\r\n%@\r\n%@\n",BRangeDay,SRangeDay,Bratio,Sratio];
						//NSLog(@"%@",para);
						[para writeToFile:newdirpath_single_tradesystem_ParaFile atomically:YES encoding:NSUTF8StringEncoding error:nil];
					}	
					
					
					
					
					
				}
								
				//製作總表
				if ([tradesystem isEqualToString:@"MESA"]){
					
				 	write_all=[write_all stringByAppendingFormat: @"%@\t%@\t%@\t%@\t%@\t%@\t%@\t%@\t%@\t%@\n",	code,FastLim,SlowLim,winpercentage,yearreturn,count,startdate,enddate,id_class,id_country ] ;
					//如果此行出現錯誤 表示可能資料輸出過大,可以採用直接將資料從SQLite Database Browser 輸出
                    //方法如下:先File ->Open 
                    //          File->Export->Table as CSV File->到ＥＸＣＥＬ將資料取出
					
					
					
				}				
				else if([tradesystem isEqualToString:@"LF"]){				
					 					
					
				}
				
				
				
				
			}
			//製作總表檔案輸出
			//NSLog(@"%@",write_all);
			 NSString *path_all_file=[newdirpath_all stringByAppendingFormat:@"/%@.txt",[NSString stringWithFormat:@"%@_%@_%@\n",tradesystem,aindex,adwm]];
			 [write_all writeToFile:path_all_file atomically:YES encoding:NSUnicodeStringEncoding error:nil];
			
            
            //NSUnicodeStringEncoding 輸出中文化
			
			
		}
		sqlite3_finalize(stm);		
		
		
	}

		
	
	[pool release];
}
 




#pragma mark -
#pragma mark  讀取資料
-(void)opt_datasql_code_name:(NSString *) country titels:(NSString *)titles{
	
	//從資料庫取出資料
	const char *sql = NULL;	
	//設定要執行篩選的ＳＬＱ敘述
	NSMutableArray *temp_all_code;
	NSMutableArray *temp_all_name;
	NSMutableArray *temp_all_class;
	
	
    NSString *tsql;
	
	tsql=@"SELECT id,Symbol,Lname,Ename,Class FROM ";
	tsql=[tsql stringByAppendingString:country];
	sql=[tsql UTF8String];
	
	temp_all_code=[[[NSMutableArray alloc] init] autorelease];
	temp_all_name=[[[NSMutableArray alloc] init] autorelease];
	temp_all_class=[[[NSMutableArray alloc] init] autorelease];
	
 
	NSString *ver;
	ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
	ver=[ver stringByReplacingOccurrencesOfString:@"." withString:@"_"];
	NSString *filename;
	filename=@"data_";
	filename=[filename stringByAppendingString:ver];
	NSString *filenamexx;
	filenamexx=@"sqlite3";
	NSString *fullfilename;
	fullfilename=[filename stringByAppendingString:@"."];
	fullfilename=[fullfilename stringByAppendingString:filenamexx];
	DBHelper *helper =[DBHelper newInstance:filename andEXT:filenamexx andfullname:fullfilename];
	
	sqlite3 *database = [helper openDatabase]; 
	sqlite3_stmt *stm;
	
	if(sqlite3_prepare_v2(database, sql, strlen(sql), &stm, NULL)== SQLITE_OK) {
		
		while(sqlite3_step(stm) ==SQLITE_ROW)
		{
			
			
			char *field1=(char *)sqlite3_column_text(stm, 1);
			NSString *ss1=[[NSString alloc]initWithUTF8String:field1];
			[temp_all_code addObject:ss1];				
			[ss1 release];
			
			//2:名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs  boolForKey:@"localize Name" ];
			
			if ((BOOL)[prefs  boolForKey:@"localize Name" ]==YES) {
				//表示使用當地語言的名稱
				char *field2=(char *)sqlite3_column_text(stm, 2);
				NSString *ss2=[[NSString alloc]initWithUTF8String:field2];
				[temp_all_name addObject:ss2];
				[ss2 release];
			} 
			else {
				//表示採用英語當作名稱
				char *field2=(char *)sqlite3_column_text(stm, 3);
				NSString *ss2=[[NSString alloc]initWithUTF8String:field2];
				[temp_all_name addObject:ss2];
                [ss2 release];
			}
			//分類
			char *field4=(char *)sqlite3_column_text(stm, 4);
			NSString *ss4=[[NSString alloc]initWithUTF8String:field4];
			[temp_all_class addObject:ss4];
            [ss4 release];
		}
		//code_array=tcode_array;
	}
	 
	//儲存自選股
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *dir = [paths objectAtIndex:0];
	NSString *filePathw;
 
	
	filePathw = [[[NSString alloc] initWithString:[dir stringByAppendingPathComponent:[NSString stringWithFormat: @"WatchList_%@%@.cplist",titles,country]]] autorelease];
	NSMutableArray *awr;
	awr=[[[NSMutableArray alloc] init] autorelease];
	
	/*
	for (int i=0; i<[temp_all_code count]; i++) {
		NSString *wr;
		wr=[NSString stringWithFormat:@"%@_%@_2010/11/14_34.5_56000",[temp_all_code objectAtIndex:i],[temp_all_name objectAtIndex:i]];
		[awr addObject:wr];
	}
	*/
	
	for (int i=0; i<[temp_all_code count]; i++) {
		NSString *wr;
		wr=[NSString stringWithFormat:@"%@_%@_%@_34.5_56000",[temp_all_code objectAtIndex:i],[temp_all_name objectAtIndex:i], [temp_all_class objectAtIndex:i]];
		[awr addObject:wr];
	}	
	
	[awr writeToFile:filePathw atomically:NO];	
	
	
	
	//結束查詢作業
	sqlite3_finalize(stm);
	 
	 
	
	//儲存群組
	filePathw = [[[NSString alloc] initWithString:[dir stringByAppendingPathComponent:@"WatchListClass.cplist"]] autorelease];
	NSMutableArray *watchc=nil;
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	if ([fileManager fileExistsAtPath:filePathw] == YES)
	{
	 watchc= [[[NSMutableArray alloc] initWithContentsOfFile:filePathw] autorelease];
	}
	NSString *name;
	name=titles; //@"最佳化群組_"; 
	
	
	
	
	if ([watchc indexOfObject:[name stringByAppendingString: country]]==NSNotFound) {
		[watchc addObject:[name stringByAppendingString: country]];
	}
	[watchc writeToFile:filePathw atomically:NO];	
	
	
}





#pragma mark -
#pragma mark  最佳化參數歸零
-(void)resetOptimizePara{
	NSLog(@"重置資料庫");
	NSLog(@"最佳化資料庫表格刪除");
	//啓動資料庫檔案 輸入檔名與副執行檔名稱與全名
	//DBHelper *helper =[DBHelper newInstance:@"data1" andEXT:@"sqlite3" andfullname:@"data1.sqlite3"];
	NSString *ver;
	ver=[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
	ver=[ver stringByReplacingOccurrencesOfString:@"." withString:@"_"];
	NSString *filename;
	filename=@"data_";
	filename=[filename stringByAppendingString:ver];
	NSString *filenamexx;
	filenamexx=@"sqlite3";
	NSString *fullfilename;
	fullfilename=[filename stringByAppendingString:@"."];
	fullfilename=[fullfilename stringByAppendingString:filenamexx];
	DBHelper *helper =[DBHelper newInstance:filename andEXT:filenamexx andfullname:fullfilename];		
	sqlite3 *database = [helper openDatabase];				
	
	const char *update_sql = NULL;	
	NSString *update_tsql;
	char *errorMsg;				
	//LF
	{
		update_tsql=@"DROP TABLE LF_0_d";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE LF_0_w";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE LF_0_m";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE LF_1_d";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE LF_1_w";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE LF_1_m";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);				
		
		update_tsql=@"DROP TABLE LF_2_d";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE LF_2_w";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE LF_2_m";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);		
	}
	//mesa
	{
		update_tsql=@"DROP TABLE MESA_0_d";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE MESA_0_w";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE MESA_0_m";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE MESA_1_d";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE MESA_1_w";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE MESA_1_m";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);				
		
		update_tsql=@"DROP TABLE MESA_2_d";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE MESA_2_w";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"DROP TABLE MESA_2_m";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);		
	}		
	
	
	//MESA
	{
		update_tsql=@"CREATE TABLE MESA_0_d  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT );";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE MESA_0_w  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE MESA_0_m  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE MESA_1_d  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE MESA_1_w  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE MESA_1_m  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"CREATE TABLE MESA_2_d  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE MESA_2_w  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE MESA_2_m  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, FastLim TEXT, SlowLim TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		
	}
	//LF
	{
		update_tsql=@"CREATE TABLE LF_0_d  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT ,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE LF_0_w  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE LF_0_m  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE LF_1_d  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE LF_1_w  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE LF_1_m  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);	
		
		update_tsql=@"CREATE TABLE LF_2_d  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE LF_2_w  (id INTEGER PRIMARY KEY AUTOINCREMENT , c	ode TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
			update_sql=[update_tsql UTF8String];
			sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		update_tsql=@"CREATE TABLE LF_2_m  (id INTEGER PRIMARY KEY AUTOINCREMENT , code TEXT, BRangeDay TEXT, SRangeDay TEXT, Bratio TEXT, Sratio TEXT,winpercentage TEXT,yearreturn TEXT,count TEXT,startdate TEXT,enddate TEXT,id_class TEXT);";
		update_sql=[update_tsql UTF8String];
		sqlite3_exec(database, update_sql, NULL, NULL, &errorMsg);					
		
		
	}
	
	
	
	

}



#pragma mark -
#pragma mark  按鈕轉換
-(void)switchChange:(id) sender{
	
	UISwitch *onoff = (UISwitch *) sender;	
	
	
	switch (onoff.tag) {
		case 100:{
			//搜尋是否要使用名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setBool:onoff.on  forKey:@"isActiveOptimize"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			 
			 			
			break;
		}
		case 300:{
			//搜尋是否要使用名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setBool:onoff.on  forKey:@"isWriteToTXT"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			 
			
			break;
		}
		case 400:{
			//搜尋是否要使用名稱
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setBool:onoff.on  forKey:@"isShowPara"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			 
			
			break;
		}
			
		default:
			break;
	}
	
	
	
	
	
}


-(void)segChange:(id) sender{
	 
	UISegmentedControl *sega = (UISegmentedControl *) sender;	
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	[prefs setInteger:sega.selectedSegmentIndex forKey:@"isActiveOptimize_dwm"];
	[prefs synchronize];	
	
	 
	
}
#pragma mark -
#pragma mark  日期挑選器改變值
-(void) changeDate:(UIDatePicker *) picker{
   
	 
	NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
	[prefs setObject:[picker date] forKey:@"startOptimizeDate"];
	[prefs synchronize];	
	
	[myTable reloadData];
	
		
	
}
#pragma mark -
#pragma mark  策略選擇器

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
	return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
	
	switch (TableSelectRow) {
		case 3:{
			NSLog(@"3 最佳化模型");	
			return [tradesystemaray count];
			break;
		}
		case 4:{
			NSLog(@"3 最佳化模型");	
			return [tradeIndex count];
			break;
		}			
			
			
		case 5:{
			NSLog(@"4 停損出場率");	
			return [stopratearay count];
			break;
		}
		case 6:{
			
			NSLog(@"5 買賣手續費率");	
		  return [costfeeratearay count];
			break;
		}
		case 7:{
			
			NSLog(@"6 多空或雙向策略");	
			return [buysellboth count];
			break;
		}			
		case 8:{
			
			NSLog(@"7 進出場時間選擇");	
			return [enterTime count];
			break;
		}				
		case 9:{
			
			NSLog(@"8 進出場價格選擇");	
			return [enterprice count];
			break;
		}		
		case 10:{
			
			NSLog(@"9 進出場價格選擇");	
			return [enternumber count];
			break;
		}		
			
			
		 
	}	
	return 0;
	
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
	
	
	switch (TableSelectRow) {
		case 3:{
			NSLog(@"3 最佳化模型");	
			return [tradesystemaray objectAtIndex:row] ;
			break;
		}
		case 4:{
			NSLog(@"3 最佳化模型");	
			return [tradeIndex objectAtIndex:row] ;
			break;
		}
			
			
			
		case 5:{
			NSLog(@"4 停損出場率");	
			return [stopratearay objectAtIndex:row] ;
			break;
		}
		case 6:{
			
			NSLog(@"5 買賣手續費率");	
		   return [costfeeratearay objectAtIndex:row] ;
			break;
		}
		case 7:{
			
			NSLog(@"7 多空或雙向策略");	
			return [buysellboth objectAtIndex:row] ;
			break;
		}
		case 8:{
			
			NSLog(@"8 進出場時間選擇");	
			return [enterTime objectAtIndex:row] ;
			break;
		}
		case 9:{
			
			NSLog(@"8 進出場價格選擇");	
			return [enterprice objectAtIndex:row] ;
			break;
		}
		case 10:{
			
			NSLog(@"9 進出場數量選擇");	
			return [enternumber objectAtIndex:row] ;
			break;
		}
			
		 
	}		
	
	return @"";
	
	
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
	 
	
		
	switch (TableSelectRow) {
		case 3:{
			NSLog(@"3 最佳化模型=%@",[tradesystemaray objectAtIndex:row]);	
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[tradesystemaray objectAtIndex:row] forKey:@"OptimizeTradeSystem"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			//針對ＭＥＳＡ與ＬＦ固定買賣點
			if ([[tradesystemaray objectAtIndex:row] isEqualToString:@"MESA"]) {
				[prefs setObject:@"後一日" forKey:@"enterTime"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 				
				
				[prefs setObject:@"開盤價" forKey:@"enterprice"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
				
				
				[myTable reloadData];
			}
			if ([[tradesystemaray objectAtIndex:row] isEqualToString:@"LF"]) {
				[prefs setObject:@"當日" forKey:@"enterTime"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 				
				
				[prefs setObject:@"收盤價" forKey:@"enterprice"];
				[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
				
				
				[myTable reloadData];
			}			
			
			
			break;
		}
		case 4:{
			NSLog(@"4 停損出場率");	
			 
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[tradeIndex objectAtIndex:row] forKey:@"tradeindex"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			
			
			break;
		}		
		
		
		
		case 5:{
			NSLog(@"4 停損出場率");	
			//return [stopratearay objectAtIndex:row] ;
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[stopratearay objectAtIndex:row] forKey:@"Optimizestopratearay"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			
			
			break;
		}
		case 6:{
			
			NSLog(@"5 買賣手續費率");	
			//return [costfeeratearay objectAtIndex:row] ;
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[costfeeratearay objectAtIndex:row] forKey:@"Optimizescostfeeratearay"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			
			
			break;
		}
		case 7:{
			
			NSLog(@"7 多空或雙向策略");	
			 
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[buysellboth objectAtIndex:row] forKey:@"buysellboth"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			
			
			break;
		}
		case 8:{
			
			NSLog(@"8 進出場時間選擇");	
			
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[enterTime objectAtIndex:row] forKey:@"enterTime"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			
			
			break;
		}
		case 9:{
			
			NSLog(@"9 進出場價格選擇");	
			
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[enterprice objectAtIndex:row] forKey:@"enterprice"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			
			break;
		}			
		case 10:{
			
			NSLog(@"9 進出場價格選擇");	
			
			NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
			[prefs setObject:[enternumber objectAtIndex:row] forKey:@"enternumber"];
			[prefs synchronize];	//將記憶體中的資料存到硬體上 儲存指令 			
			
			
			break;
		}					
			
			
	}		
	
	
	
	
	
	
	 
    [myTable reloadData];
}


/*
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component{

}
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{

}
 

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{

}


*/



#pragma mark -
#pragma mark  其他

- (void)dealloc {	
	
	[myTable release];
	[SearchCondition release];
 
	[super dealloc];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}




@end
